package cn.iocoder.yudao.module.design.aop;

import cn.iocoder.yudao.module.design.annotation.SplitToList;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
@Component
public class SplitToListAnnotationProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            SplitToList  annotation = field.getAnnotation(SplitToList.class);
            if (annotation != null) {
                String fieldName = annotation.value();
                String separator = annotation.separator();
                try {
                    field.setAccessible(true);
                    String fieldValue = (String) field.get(bean);
                    List<String> valueList = Arrays.asList(fieldValue.split(separator));
                    field.set(bean, valueList);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Failed to split field value: " + e.getMessage());
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}